package artexercise;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 习题类 - 完全兼容版本
 */
public class Exercise {
    private List<ArithmeticExpression> expressions;
    private Random random;

    public Exercise() {
        this.expressions = new ArrayList<>();
        this.random = new Random();
    }

    // 产生一定数量的加法习题
    public void generateAdditionExercises(int count) {
        System.out.println("正在生成 " + count + " 道加法题...");
        for (int i = 0; i < count; i++) {
            AdditionExpression expr;
            do {
                int op1 = random.nextInt(50) + 1;
                int op2 = random.nextInt(50) + 1;
                expr = new AdditionExpression(op1, op2);
            } while (!expr.isValid());

            expressions.add(expr);
        }
    }

    // 产生一定数量的减法习题
    public void generateSubtractionExercises(int count) {
        System.out.println("正在生成 " + count + " 道减法题...");
        for (int i = 0; i < count; i++) {
            SubtractionExpression expr;
            do {
                int op1 = random.nextInt(100) + 1;
                int op2 = random.nextInt(50) + 1;
                expr = new SubtractionExpression(op1, op2);
            } while (!expr.isValid());

            expressions.add(expr);
        }
    }

    // 产生加减法混合习题
    public void generateMixedExercises(int count) {
        System.out.println("正在生成 " + count + " 道混合题...");
        for (int i = 0; i < count; i++) {
            ArithmeticExpression expr = null;
            boolean isValid = false;

            while (!isValid) {
                if (random.nextBoolean()) {
                    int op1 = random.nextInt(50) + 1;
                    int op2 = random.nextInt(50) + 1;
                    expr = new AdditionExpression(op1, op2);
                } else {
                    int op1 = random.nextInt(100) + 1;
                    int op2 = random.nextInt(50) + 1;
                    expr = new SubtractionExpression(op1, op2);
                }
                isValid = expr.isValid();
            }

            expressions.add(expr);
        }
    }

    // 辅助方法：创建重复字符串（替代String.repeat）
    private String createRepeatString(String str, int count) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            sb.append(str);
        }
        return sb.toString();
    }

    // 格式化显示所有习题 - 优化排版，每行显示多个题目
    public void displayFormatted() {
        System.out.println("\n" + createRepeatString("=", 60));
        System.out.println("                   算术练习题");
        System.out.println(createRepeatString("=", 60));

        int columns = 3; // 每行显示3个题目
        for (int i = 0; i < expressions.size(); i++) {
            ArithmeticExpression expr = expressions.get(i);

            // 格式化每个题目，固定宽度
            String formatted = String.format("%2d. %-15s", i + 1, expr.toString());
            System.out.print(formatted);

            // 每行显示columns个题目后换行
            if ((i + 1) % columns == 0) {
                System.out.println();
            }
        }

        // 如果最后一行不满，补全空位
        if (expressions.size() % columns != 0) {
            System.out.println();
        }

        System.out.println(createRepeatString("=", 60));
        System.out.println("总计: " + expressions.size() + " 道题");
    }

    // 显示带答案的习题 - 优化排版
    public void displayWithAnswers() {
        System.out.println("\n" + createRepeatString("=", 75));
        System.out.println("                      算术练习题（含答案）");
        System.out.println(createRepeatString("=", 75));

        int columns = 2; // 带答案的题目每行显示2个
        for (int i = 0; i < expressions.size(); i++) {
            ArithmeticExpression expr = expressions.get(i);

            // 格式化带答案的题目，固定宽度
            String formatted = String.format("%2d. %-25s", i + 1, expr.toFullString());
            System.out.print(formatted);

            // 每行显示columns个题目后换行
            if ((i + 1) % columns == 0) {
                System.out.println();
            }
        }

        // 如果最后一行不满，补全空位
        if (expressions.size() % columns != 0) {
            System.out.println();
        }

        System.out.println(createRepeatString("=", 75));
        System.out.println("总计: " + expressions.size() + " 道题");
    }

    // 将习题保存到文件
    public void saveToFile(String filename, boolean withAnswers) {
        try {
            java.io.PrintWriter writer = new java.io.PrintWriter(filename);

            if (withAnswers) {
                writer.println(createRepeatString("=", 75));
                writer.println("                      算术练习题（含答案）");
                writer.println(createRepeatString("=", 75));

                int columns = 2;
                for (int i = 0; i < expressions.size(); i++) {
                    ArithmeticExpression expr = expressions.get(i);
                    String formatted = String.format("%2d. %-25s", i + 1, expr.toFullString());
                    writer.print(formatted);

                    if ((i + 1) % columns == 0) {
                        writer.println();
                    }
                }

                if (expressions.size() % columns != 0) {
                    writer.println();
                }
            } else {
                writer.println(createRepeatString("=", 60));
                writer.println("                   算术练习题");
                writer.println(createRepeatString("=", 60));

                int columns = 3;
                for (int i = 0; i < expressions.size(); i++) {
                    ArithmeticExpression expr = expressions.get(i);
                    String formatted = String.format("%2d. %-15s", i + 1, expr.toString());
                    writer.print(formatted);

                    if ((i + 1) % columns == 0) {
                        writer.println();
                    }
                }

                if (expressions.size() % columns != 0) {
                    writer.println();
                }
            }

            writer.println(createRepeatString("=", withAnswers ? 75 : 60));
            writer.println("总计: " + expressions.size() + " 道题");
            writer.close();

            System.out.println("✓ 习题已保存到文件: " + filename);
        } catch (java.io.FileNotFoundException e) {
            System.out.println("❌ 保存文件时出错: " + e.getMessage());
        }
    }

    // 获取习题数量
    public int getExerciseCount() {
        return expressions.size();
    }

    // 获取指定位置的习题
    public ArithmeticExpression getExpression(int index) {
        if (index >= 0 && index < expressions.size()) {
            return expressions.get(index);
        }
        return null;
    }

    // 清空习题
    public void clear() {
        expressions.clear();
    }
}